package com.jiazhong.mingxing.project.bookstore.front.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiazhong.mingxing.project.bookstore.commons.bean.Address;
import com.jiazhong.mingxing.project.bookstore.commons.config.JwtConfig;
import com.jiazhong.mingxing.project.bookstore.commons.mapper.AddressMapper;
import com.jiazhong.mingxing.project.bookstore.commons.util.JsonResult;
import com.jiazhong.mingxing.project.bookstore.commons.util.ResultTool;
import com.jiazhong.mingxing.project.bookstore.front.service.AddressService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {
    @Resource
    private AddressMapper addressMapper;

    @Override
    public JsonResult findAddressByUserId(HttpServletRequest request) {
        // 1. 获取到user_id
        String token = request.getHeader("token");
        String id = JwtConfig.parseJWT(token).get("id").toString();
        // 2. 查询操作
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", id);
        List<Address> addresses = addressMapper.selectList(queryWrapper);
        return ResultTool.success(addresses);
    }

    @Transactional(rollbackFor = Exception.class)
    public JsonResult saveAddress(Address address, HttpServletRequest request) {
        // 1. 获取到user_id
        String token = request.getHeader("token");
        String id = JwtConfig.parseJWT(token).get("id").toString();
        address.setUserId(id);
        // 2. 如果添加的是常用地址信息，修改原有的常用地址为非常用地址
        if (address.getState() == 1) {
            UpdateWrapper<Address> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("state", "1");
            updateWrapper.eq("user_id", id);
            updateWrapper.set("state", "0");
            addressMapper.update(updateWrapper);
        }

        // 3. 添加用户地址信息
        addressMapper.insert(address);
        return ResultTool.success("success");
    }
}
